package mwa.cs.rc.ctrl;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mwa.cs.dao.RcTransMDAO;
import mwa.cs.dao.ReceiveCodeDAO;
import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.database.Database;
import mwa.cs.model.RcTransD;
import mwa.cs.model.RcTransM;
import mwa.cs.util.JDate;

public class CS54002Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private int vnSiteId;
	private int vnUserId;
	private String vaUrlAddress;
	private String vaAgentBrowser;
       
    public CS54002Srvl() {
        super();
    }

	public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
		vaUrlAddress = request.getParameter("url_address");
		vaAgentBrowser = request.getParameter("agent_browser");
		
		String vaBtnCancel = request.getParameter("btn_cancel");
		if ( vaBtnCancel == null){
			vaBtnCancel ="no";
		}
		String vaStatusCancelButton = "btn_enable";
		String vaErrorMsg = "no" , vaAlreadyColse = "no";
		Database db = new Database();
		RcTransMDAO voRcTransMDAO = new RcTransMDAO(db);	
		if ( vaBtnCancel.trim().equals("yes") ){
			try {
				db.beginTransaction();
				voRcTransMDAO.UpdateColseDateIsNull( vnSiteId, vnUserId);
				db.commit();
				// ไม่พบรายการ ยกเลิกการปิดการรับเงินประจำวัน
				vaErrorMsg = "yes";
				vaStatusCancelButton = "btn_disable";
			} catch (Exception e) {
				SMErrorLogDAO.getInstance().addLog(0, "CS54002", JDate.getDate(), JDate.getTime(),vnUserId, "CS54002Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
	    		db.rollback();
	    	} 
		} else {
			int voAlreayClosedResult =  voRcTransMDAO.findExistDataIsAlreadyClosed(vnSiteId, vnUserId);
			if (voAlreayClosedResult != 0){
				// มีการปิดการรับเงินประจำวันแล้ว
				vaAlreadyColse = "yes";
				vaStatusCancelButton = "btn_enable";
				loadDataFirstInComing(request, response, vaStatusCancelButton, vaAlreadyColse);
			} else {
				// ไม่พบรายการ ยกเลิกการปิดการรับเงินประจำวัน
				vaErrorMsg = "yes";
				vaStatusCancelButton = "btn_disable";
			}
		}
		db.close();
		request.setAttribute("vaErrorMsg", vaErrorMsg);
    	RequestDispatcher voRequestDispatcher = request.getRequestDispatcher("CS54002.jsp");
    	voRequestDispatcher.forward(request, response); 
	}
    
	private void loadDataFirstInComing(HttpServletRequest request, HttpServletResponse response, String vaStatusSaveButton, String vaAlreadyColse) throws ServletException, IOException {
		Database db = new Database();
		RcTransMDAO voRcTransMDAO = new RcTransMDAO(db);
		ReceiveCodeDAO voReceiveCodeDAO = new ReceiveCodeDAO(db);
		double vnSumRow21 = 0.00;
		// Step1 ReceiveCode != 21
		double vnTotalPenalty = voRcTransMDAO.sumPenaltyForCancelByReceiveEmployee(vnSiteId, vnUserId);
		ArrayList<RcTransM> voStepOneReceiveCodeNot21List = new ArrayList<RcTransM>();
		List<Map<String ,Object>> voVatAndBillAmount = null;
		List<Map<String ,Object>> voReceiveCodeIs21 = null ;
		if ( vaAlreadyColse.equals("yes")){
			voVatAndBillAmount = voRcTransMDAO.sumVatAmountAndBillAmountIsCurrentDate(vnSiteId, vnUserId);
			voReceiveCodeIs21 = voRcTransMDAO.sumVatAmountAndBillAmountReceiveCodeIs21IsCurrentDate(vnSiteId, vnUserId);
		}
		for (int i = 0; i < voVatAndBillAmount.size(); i++ ){
			Map<String, Object> voObject = voVatAndBillAmount.get(i);
			String vaReceiveCodeTemp = voObject.get("RECEIVE_CODE").toString();
			vaReceiveCodeTemp = voReceiveCodeDAO.getDescriptionByReceiveCode(vnSiteId, vaReceiveCodeTemp);
			double vnVatTotal = Double.parseDouble(((BigDecimal)voObject.get("VAT_TOTAL")).toString());
			double vnBillAmountTotal = Double.parseDouble(((BigDecimal)voObject.get("BILL_TOTAL")).toString());
			vnSumRow21 += (vnBillAmountTotal-vnVatTotal);
			RcTransM voRcTransM = new RcTransM();
			voRcTransM.setVaReceiveDate(vaReceiveCodeTemp);
			voRcTransM.setVnVatAmount(vnVatTotal);
			voRcTransM.setVnGrossAmount(vnBillAmountTotal);
			voStepOneReceiveCodeNot21List.add(voRcTransM);
		}
		// Step1 ReceiveCode == 21
		RcTransD voStepOneReceiveCode21 = new RcTransD();
		for (int i = 0; i < voReceiveCodeIs21.size(); i++ ){
			Map<String, Object> voObject = voReceiveCodeIs21.get(i);
			double vnVatTotal = Double.parseDouble(((BigDecimal)voObject.get("VAT_TOTAL")).toString());
			double vnAmount = Double.parseDouble(((BigDecimal)voObject.get("CHARGE_AND_FEE")).toString());
			double vnGarbage = Double.parseDouble(((BigDecimal)voObject.get("GARGEBAGE")).toString());
			double vnWateWater = Double.parseDouble(((BigDecimal)voObject.get("WASTEWATER")).toString());
			double vnOther = Double.parseDouble(((BigDecimal)voObject.get("OTHER_CHARGE")).toString());
			vnSumRow21 = vnVatTotal + vnAmount + vnGarbage + vnWateWater + vnOther + vnSumRow21;
			voStepOneReceiveCode21.setVnVatAmount(vnVatTotal);
			voStepOneReceiveCode21.setVnBillAmount(vnAmount);
			voStepOneReceiveCode21.setVnGarbageCharge(vnGarbage);
			voStepOneReceiveCode21.setVnWasteWaterCharge(vnWateWater);
			voStepOneReceiveCode21.setVnOtherCharge(vnOther);
		}
		request.setAttribute("voStepOneReceiveCodeNot21List", voStepOneReceiveCodeNot21List);
		request.setAttribute("voStepOneReceiveCode21", voStepOneReceiveCode21);
		request.setAttribute("vnTotalPenalty", vnTotalPenalty);
		request.setAttribute("vnSumRow21", vnSumRow21);	
		db.close();
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
